package com.source.zxingproject.zxing;

import android.content.Intent;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;

import com.google.zxing.Result;
import com.source.zxingproject.R;
import com.source.zxingproject.zxing.android.BeepManager;
import com.source.zxingproject.zxing.android.CaptureActivityHandler;
import com.source.zxingproject.zxing.android.InactivityTimer;
import com.source.zxingproject.zxing.camera.CameraManager;
import com.source.zxingproject.zxing.common.Constant;
import com.source.zxingproject.zxing.common.ZxingConfig;
import com.source.zxingproject.zxing.view.ViewfinderView;

import java.io.IOException;


/**
 * ZXing扫码
 * 该页面只做数据扫描，不做业务处理，扫描后将数据返回给调用方
 * 调用该页面前请申请相机权限
 *
 * @declare :扫一扫
 */
public class CaptureActivity extends AppCompatActivity implements SurfaceHolder.Callback {
    public static CaptureActivity captureActivity;
    public ZxingConfig config;
    private SurfaceView previewView;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;
    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private SurfaceHolder surfaceHolder;
    //从哪里跳转过来，如果需要扩展，自定义对应的值。0：集结疏散车队绑定；1：集结疏散设备绑定
    private int fromWhere = -1;

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*先获取配置信息*/
        captureActivity = this;
//        fullScreen(captureActivity);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        try {
            config = (ZxingConfig) getIntent().getExtras().get(Constant.INTENT_ZXING_CONFIG);
        } catch (Exception e) {
            Log.e("TAG", e.toString());
        }
        if (config == null) {
            config = new ZxingConfig();
        }

        //配置扫描页面属性
        config.setScanLineColor(R.color.color_86c312);
        config.setReactColor(R.color.color_86c312);
//        config.setFullScreenScan(true);
//        config.setShowFrameLine(false);
//        config.setShowReact(false);
//        config.setShowScanLine(false);
//        config.setShowMaskColor(false);
//        config.setShowStatusText(false);

        setContentView(R.layout.activity_capture);
        initIntent(getIntent());
        initView();
        initCamera();
    }

    private void initIntent(Intent intent) {
        if (intent != null) {
            fromWhere = intent.getIntExtra("FromWhere", -1);
        }
    }

    private void initView() {
        previewView = findViewById(R.id.preview_view);
        viewfinderView = findViewById(R.id.viewfinder_view);
        viewfinderView.setZxingConfig(config);
    }

    /**
     * @param pm
     * @return 是否有闪光灯
     */
    public static boolean isSupportCameraLedFlash(PackageManager pm) {
        if (pm != null) {
            FeatureInfo[] features = pm.getSystemAvailableFeatures();
            if (features != null) {
                for (FeatureInfo f : features) {
                    if (f != null && PackageManager.FEATURE_CAMERA_FLASH.equals(f.name)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * @param rawResult 返回的扫描结果
     */
    public void handleDecode(Result rawResult) {
        inactivityTimer.onActivity();
        beepManager.playBeepSoundAndVibrate();
        if (rawResult.getText() == null || TextUtils.isEmpty(rawResult.getText())) {
            //            数据为空，不往下执行
            return;
        }
        Toast.makeText(this, rawResult.getText(), Toast.LENGTH_SHORT).show();
        Log.e("TAG", "   rawResult.getText()==" + rawResult.getText());

    }

    private void switchVisibility(View view, boolean b) {
        if (b) {
            view.setVisibility(View.VISIBLE);
        } else {
            view.setVisibility(View.GONE);
        }
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        initCamera();
//    }

    private void initCamera() {
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        beepManager.setPlayBeep(config.isPlayBeep());
        beepManager.setVibrate(config.isShake());
        cameraManager = new CameraManager(getApplication(), config);
        viewfinderView.setCameraManager(cameraManager);
        handler = null;
        surfaceHolder = previewView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            // 重置callback，等待surfaceCreated()来初始化camera
            surfaceHolder.addCallback(this);
        }
        beepManager.updatePrefs();
        inactivityTimer.onResume();
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            return;
        }
        try {
            // 打开Camera硬件设备
            cameraManager.openDriver(surfaceHolder);
            // 创建一个handler来打开预览，并抛出一个运行时异常
            if (handler == null) {
                handler = new CaptureActivityHandler(this, cameraManager);
            }
        } catch (IOException ioe) {
            Log.e("TAG", ioe.toString());
        } catch (RuntimeException e) {
            Log.e("TAG", "Unexpected error initializing camera", e);
        }
    }

    @Override
    protected void onPause() {
//        Log.e("TAG","onPause");
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        if (inactivityTimer != null) {
            inactivityTimer.onPause();
        }
        if (beepManager != null) {
            beepManager.close();
        }
        if (cameraManager != null) {
            cameraManager.closeDriver();
        }
        if (!hasSurface && surfaceHolder != null) {
            surfaceHolder.removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (inactivityTimer != null) {
            inactivityTimer.shutdown();
        }
        viewfinderView.stopAnimator();
        super.onDestroy();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

}
